package com.zeeephr.core;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.SAXException;

import com.zeeephr.core.bean.Conf;
import com.zeeephr.core.sax.ConfHandler;
import com.zeeephr.core.sax.WebHandler;
import com.zeeephr.core.util.Utils;

public class Server{
	ServerSocket serverSocket=null;
	public static Utils tool;
	WebHandler myHandler;
	private static ConfHandler confHandler;
	private static SAXParserFactory factory=SAXParserFactory.newInstance();
	private static SAXParser parser;
	public static Conf conf;
	
	int threadId=0;
	static {
		try {
			confHandler=new ConfHandler();
			parser = factory.newSAXParser();
			System.out.println(Thread.currentThread().getContextClassLoader().getResource("").getPath());
			InputStream input=new FileInputStream("conf.xml");
			parser.parse(input, confHandler);
			conf=confHandler.getConf();
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public static void main(String[] args) {
		
		Server m=new Server();
		m.parseWebXml();
		m.start();
	}
	private void start() {
		System.out.println("服务器开始启动");
		try {
			serverSocket=new ServerSocket(conf.getPort());
			System.out.println("服务器开启一个ServerSocket 并占用端口:"+conf.getPort());
			System.out.println("开始等待接收客户端信息");
			while(true) {
				Socket client=serverSocket.accept();
				String clientAddress=new String(client.getInetAddress().getAddress());
				System.out.println("接收到"+clientAddress+":"+client.getPort()+"客户端的请求");
				threadId++;
				System.out.println("开启第"+threadId +"个线程进行处理");
				new Thread(new Dispartcher(client)).start();
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			System.out.println("服务器启动失败");
			e.printStackTrace();
		}
		
	}
	private void run() {
		
	}
	private void end() {
		
	}

	/*
	 * 将web工程中的web.xml中servlet类位置信息提取到tool中
	 * 可以使用tool.getPattern(String url)获取Servlet的全限定名称
	 */
	private void parseWebXml() {
		
		myHandler=new WebHandler();
		try {
			
			parser.parse(Thread.currentThread().getContextClassLoader().
					getSystemResourceAsStream("com/zeeephr/textweb/web.xml"), myHandler);
			
		}  catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			System.out.println("解析错误");
			e.printStackTrace();
		}
		tool=new Utils(myHandler.getClzs(),myHandler.getClzMappers());
	}
	
	
	
}
